<template>
  <div v-loading="loading">
    <div class="config-step">
      <px-button type="primary" :icon="ArrowLeft" class="back-btn" @click="goBack">返回</px-button>
      <div class="step-container">
        <px-steps :space="200" :active="activeStep" align-center>
          <px-step title="基本信息" @click="toStep1" />
          <px-step title="考试对象" @click="toStep2" />
          <px-step title="题目设置" @click="toStep3" />
        </px-steps>
      </div>
      <div class="step-form">
        <!-- step1 -->
        <div v-show="activeStep === 0">
          <px-form ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-position="right" label-width="150px">
            <px-row>
              <px-col :span="12">
                <px-form-item label="考试名称" prop="name">
                  <px-input v-model="baseForm.name" maxLength="40" placeholder="请输入考试名称" />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="考试类别" prop="type">
                  <px-select v-model="baseForm.type" style="width: 100%" placeholder="请选择考试类别" clearable>
                    <px-option v-for="item in typeList" :key="item.value" :label="item.name" :value="item.name" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="12">
                <px-form-item label="科室" prop="className">
                  <px-select v-model="baseForm.className" style="width: 100%" placeholder="请选择科室" clearable>
                    <px-option v-for="item in classNameList" :key="item.value" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="考试次数" prop="count">
                  <px-input-number v-model="baseForm.count" :min="0" placeholder="请输入考试次数" style="width: 100%" />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="12">
                <px-form-item label="总分" prop="totalScore">
                  <px-input-number v-model="baseForm.totalScore" :min="1" placeholder="请输入总分" style="width: 100%" />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="合格分数" prop="passScore">
                  <px-input-number
                    v-model="baseForm.passScore"
                    :min="1"
                    :disabled="baseForm.totalScore === null || baseForm.totalScore === ''"
                    placeholder="请输入合格分数"
                    style="width: 100%"
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="12">
                <px-form-item label="考试时长（分钟）" prop="period">
                  <px-input-number v-model="baseForm.period" :min="1" placeholder="请输入考试时长" style="width: 100%" />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="24">
                <px-form-item label="考试介绍" prop="intruction">
                  <px-input
                    v-model="baseForm.intruction"
                    style="width: 100%"
                    type="textarea"
                    :rows="5"
                    maxlength="200"
                    placeholder="请输入考试介绍"
                    show-word-limit
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="24">
                <px-form-item label="注意事项" prop="attention">
                  <px-input
                    v-model="baseForm.attention"
                    style="width: 100%"
                    type="textarea"
                    :rows="5"
                    maxlength="200"
                    placeholder="请输入注意事项"
                    show-word-limit
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
          <div class="step-footer">
            <px-button type="primary" @click="toStep2">下一步</px-button>
          </div>
        </div>
        <!-- Step2 -->
        <div v-show="activeStep === 1">
          <div class="table-top">
            <div>
              <span>考生人数：</span>
              <span>合计</span>
              <span>{{ tableData.length }}</span>
              <span>人</span>
            </div>
            <div>
              <px-button @click="handleBatchDelete">删除</px-button>
              <px-button type="primary" @click="handleAddStudent">添加</px-button>
            </div>
          </div>
          <px-table height="calc(100vh - 420px)" :data="tableData" size="small" border class="common-table" @selection-change="step2TableSelect">
            <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
            <px-table-column prop="realName" label="姓名" min-width="120" show-overflow-tooltip />
            <px-table-column prop="empNo" label="工号" min-width="120" show-overflow-tooltip />
            <px-table-column prop="deptName" label="组织" min-width="120" show-overflow-tooltip />
            <px-table-column prop="phone" label="手机号码" min-width="120" show-overflow-tooltip />
            <px-table-column prop="planTime" label="考试计划时间" min-width="120" show-overflow-tooltip />
            <px-table-column prop="createTime" label="添加时间" min-width="100" show-overflow-tooltip />
            <px-table-column label="操作" width="120" fixed="right" align="center">
              <template #header>
                <div class="cell-title">
                  <span class="text">操作</span>
                  <px-tooltip effect="dark" content="考试次数用尽，点击重置次数按钮将考生考试次数重置为0并清空考试记录" placement="top">
                    <px-icon v-if="handleType == 'Edit'"><WarningFilled /></px-icon>
                  </px-tooltip>
                </div>
              </template>
              <template #default="scope">
                <px-tooltip content="修改计划" placement="top">
                  <px-button link icon="EditPen" type="danger" @click="handleEditPlan(scope)" />
                </px-tooltip>
                <px-tooltip content="删除" placement="top">
                  <px-button link icon="Delete" type="danger" @click="handleDeleteStudent(scope.$index)" />
                </px-tooltip>
                <px-tooltip content="重置次数" placement="top">
                  <px-button v-if="handleType == 'Edit'" link icon="Tools" type="danger" @click="handleResetStudent(scope)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
          <div class="step-footer">
            <px-button @click="toStep1">上一步</px-button>
            <px-button type="primary" @click="toStep3">下一步</px-button>
          </div>
          <div v-if="addStudentVisible">
            <AddStudent v-model:visible="addStudentVisible" @add="confirmAddStudent" />
          </div>
          <px-dialog v-model="editPlanVisible" title="修改考试计划时间" width="650">
            <px-form ref="editPlanFormRef" :model="editPlanForm">
              <px-form-item label="考试计划时间" prop="time" label-width="150">
                <px-date-picker
                  v-model="editPlanForm.time"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :disabled-date="disabledDate"
                />
              </px-form-item>
            </px-form>
            <template #footer>
              <span class="dialog-footer">
                <px-button @click="() => (editPlanVisible = false)">取消</px-button>
                <px-button type="primary" @click="saveBtn">确定</px-button>
              </span>
            </template>
          </px-dialog>
        </div>
        <!-- Step3 -->
        <div v-show="activeStep === 2">
          <div class="topic-info-title mg-b-8">
            <span class="topic-info">
              考试总分：<span :class="{ 'over-score': Number(currentScore) > Number(baseForm.totalScore) }">{{ currentScore }}</span> 分/
              {{ baseForm.totalScore }}分
            </span>
            <span class="topic-info">共计：{{ subjectTableData.length }}道题</span>
            <span class="topic-info">单选题：{{ subjectInfo("S").num }}道{{ subjectInfo("S").total }}分</span>
            <span class="topic-info">多选题：{{ subjectInfo("M").num }}道{{ subjectInfo("M").total }}分</span>
            <span class="topic-info">判断题：{{ subjectInfo("T").num }}道{{ subjectInfo("T").total }}分</span>
          </div>
          <div class="flex-center">
            <px-form ref="subjectFormRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
              <px-form-item label="题目类型" prop="subjectType">
                <px-select v-model="queryParams.subjectType" style="width: 260px" placeholder="请选择题目类型" clearable>
                  <px-option v-for="item in subjectTypeList" :key="item.value" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
              <px-form-item label="题目名称" prop="subjectName">
                <px-input v-model="queryParams.subjectName" style="width: 260px" placeholder="请输入考试名称" clearable />
              </px-form-item>
              <div class="search-form-btn">
                <px-button type="primary" @click="handleSubjectQuery">查询</px-button>
                <px-button @click="resetSubjectQuery">重置</px-button>
              </div>
            </px-form>
          </div>
          <div class="flex-center mg-b-8">
            <px-button type="primary" @click="addQuestion">新增</px-button>
            <px-button type="primary" @click="addQuestionFromBank">从题库添加</px-button>
            <px-button type="primary" @click="autoGroupQuestion">自动组卷</px-button>
            <px-button plain @click="batchDeleteSubject">删除</px-button>
          </div>
          <div v-loading="loading" class="table-content">
            <px-table
              ref="subjectTableRef"
              height="calc(100vh - 450px)"
              :data="subjectTableData"
              row-key="id"
              size="small"
              border
              class="common-table"
              @selection-change="step3TableSelect"
            >
              <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
              <px-table-column type="index" label="序号" fixed width="55" align="center" />
              <px-table-column prop="questionName" label="题目名称" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <span v-html="scope.row.questionName" />
                </template>
              </px-table-column>
              <px-table-column prop="typeName" label="题目类型" min-width="120" show-overflow-tooltip />
              <px-table-column prop="score" label="分值" min-width="80" show-overflow-tooltip />
              <px-table-column prop="updateTime" label="更新时间" min-width="100" show-overflow-tooltip />
              <px-table-column prop="updateByName" label="更新人" min-width="100" show-overflow-tooltip />
              <px-table-column label="操作" width="80" fixed="right" align="center">
                <template #default="scope">
                  <px-tooltip content="删除" placement="top">
                    <px-button link icon="Delete" type="danger" @click="handleDeleteSubject(scope.$index)" />
                  </px-tooltip>
                </template>
              </px-table-column>
              <px-table-column label="移动" width="80" fixed="right" align="center">
                <template #default="">
                  <px-tooltip content="拖拽移动" placement="top">
                    <px-button link icon="Rank" type="primary" class="drag-btn" style="cursor: move" />
                  </px-tooltip>
                </template>
              </px-table-column>
            </px-table>
          </div>
          <div class="step-footer">
            <px-button @click="toStep2">上一步</px-button>
            <px-button type="primary" @click="handleSubmit">保存</px-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增题目 -->
    <div v-if="addQuestionVisible">
      <AddQuestion v-model:visible="addQuestionVisible" :categoryList="questionTypeList" @save="saveQuestion" />
    </div>

    <!-- 从题库新增 -->
    <div v-if="addQuestionFromBankVisible">
      <AddQuestionFromBank v-model:visible="addQuestionFromBankVisible" @save="saveQuestion" />
    </div>

    <!-- 自动组卷 -->
    <div v-if="addAutoGroupExamVisible">
      <AutoGroupExam
        v-model:visible="addAutoGroupExamVisible"
        :currentScore="currentScore"
        :totalScore="totalScore"
        :totalNum="subjectTableData.length"
        :questionIds="questionIds"
        :examId="handleType === 'Edit' ? editData.examId : null"
        :getSubjectInfo="subjectInfo"
        @save="saveQuestion"
      />
    </div>
  </div>
</template>

<script setup>
import { queryCurrentClassList, queryDictData } from "@/api/common";
import { getExamConfigAPI, getQuestionCategoryListAPI, saveExamAPI, resetExamTimesAPI } from "@/api/knowledge/examManage";
import { ArrowLeft } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import Sortable from "sortablejs";
import { computed, nextTick, onMounted, reactive, ref, toRefs } from "vue";
import AddQuestion from "./addQuestion.vue";
import AddQuestionFromBank from "./addQuestionFromBank.vue";
import AddStudent from "./addStudent.vue";
import AutoGroupExam from "./autoGroupExam.vue";
import dayjs from "dayjs";

const props = defineProps({
  handleType: {
    type: String,
    default: "Add"
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["goBack"]);

const baseFormRef = ref(null);
const subjectFormRef = ref(null);
const subjectTableRef = ref(null);

const baseFormRules = computed(() => ({
  name: [{ required: true, message: "培训名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "培训类型不能为空", trigger: "change" }],
  className: [{ required: true, message: "科室不能为空", trigger: "change" }],
  count: [{ required: true, message: "考试次数不能为空", trigger: "blur" }],
  totalScore: [{ required: true, message: "总分不能为空", trigger: "blur" }],
  // passScore: [{ required: true, message: "合格分数不能为空", trigger: "blur" }],
  passScore: [{ required: true, message: "合格分数不能为空", validator: checkPassScore, trigger: "blur" }],
  period: [{ required: true, message: "考试时长不能为空", trigger: "blur" }]
}));

const questionIds = computed(() => {
  return state.subjectTableData?.map(i => i?.questionId);
});

const checkPassScore = (rule, value, callback) => {
  if (value === null || value === "") {
    callback(new Error("合格分数不能为空"));
  } else if (value > state.baseForm.totalScore) {
    callback(new Error("合格分数不能大于总分"));
  } else {
    callback();
  }
};

const subjectTypeList = ref([
  {
    name: "单选",
    value: "S"
  },
  {
    name: "多选",
    value: "M"
  },
  {
    name: "判断",
    value: "T"
  }
]);

const state = reactive({
  loading: false,
  activeStep: 0,
  typeList: [],
  questionTypeList: [],
  classNameList: [],
  baseForm: {
    name: "",
    type: null,
    className: "",
    count: null,
    totalScore: null,
    passScore: null,
    period: null,
    intruction: "",
    attention: ""
  },
  tableData: [],
  addStudentVisible: false,
  editPlanVisible: false,
  editPlanForm: {
    time: ""
  },
  tableSelectedData: [],
  editData: {},
  queryParams: {
    subjectType: "",
    subjectName: ""
  },
  subjectTableData: [],
  data_back: [],
  subjectTableSelectedData: [],
  addQuestionVisible: false,
  addQuestionFromBankVisible: false,
  addAutoGroupExamVisible: false
});
const {
  loading,
  activeStep,
  typeList,
  questionTypeList,
  classNameList,
  baseForm,
  tableData,
  addStudentVisible,
  editPlanVisible,
  editPlanForm,
  editData,
  queryParams,
  subjectTableData,
  addQuestionVisible,
  addQuestionFromBankVisible,
  addAutoGroupExamVisible
} = toRefs(state);

onMounted(() => {
  getClassNameSelect();
  getExamTypeList();
  getQuestionTypeList();
  if (props.handleType === "Edit") {
    editSearch();
  }
  nextTick(() => {
    rowDrag();
  });
});

const disabledDate = time => {
  // 禁用早于今天的日期（不含今天）
  return dayjs(time).isBefore(dayjs(), "day");
};

// 当前总分
const currentScore = computed(() => {
  let total = 0;
  if (state.subjectTableData.length > 0) {
    state.subjectTableData.forEach(item => {
      total += item.score;
    });
  } else {
    total = 0;
  }
  return total;
});

// 对应题型数量和总分
const subjectInfo = type => {
  let sData = subjectTableData.value.filter(item => item.type === type);
  let num = sData.length;
  let total = 0;
  sData.forEach(item => {
    total += item.score;
  });
  return { num, total };
};

// 表格拖拽排序
const rowDrag = () => {
  const tbody = subjectTableRef.value.$el.querySelector(".px-table__body-wrapper tbody");
  if (!tbody) return;
  Sortable.create(tbody, {
    draggable: ".px-table__row",
    onEnd: event => {
      if (event.oldIndex !== undefined && event.newIndex !== undefined) {
        const currRow = state.subjectTableData.splice(event.oldIndex, 1)[0];
        state.subjectTableData.splice(event.newIndex, 0, currRow);
      }
    }
  });
};

// 获取科室下拉框数据
const getClassNameSelect = async () => {
  classNameList.value = await queryCurrentClassList();
};

// 获取题目分类下拉框数据
const getQuestionTypeList = async () => {
  const params = {
    size: 9999,
    current: 1,
    name: ""
  };
  const res = await getQuestionCategoryListAPI(params);
  state.questionTypeList = res.records.map(item => {
    return {
      name: item.name,
      value: item.categoryId
    };
  });
};

// 获取考试类别下拉框数据
const getExamTypeList = async () => {
  const typeData = await queryDictData({ typeCode: "EXAM_TYPE" });
  state.typeList = [...typeData];
};

const handleBatchDelete = () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要删除的数据");
    return;
  }
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const a1 = state.tableData;
      const a2 = state.tableSelectedData;
      state.tableData = a1.filter(row => !a2.includes(row));
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const goBack = () => {
  emits("goBack");
};

const toStep1 = () => {
  state.activeStep = 0;
};

const toStep2 = async () => {
  try {
    const formValidate1 = await baseFormRef.value.validateField();
    if (formValidate1) {
      state.activeStep = 1;
    }
  } catch (error) {}
};

const toStep3 = async () => {
  try {
    const formValidate1 = await baseFormRef.value.validateField();
    if (!state.tableData?.length) {
      PxMessage.error("请添加考生");
      return;
    }
    if (formValidate1 && state.tableData?.length) {
      state.activeStep = 2;
    }
  } catch (error) {}
};

const handleAddStudent = () => {
  state.addStudentVisible = true;
};

const confirmAddStudent = data => {
  data?.data?.map(item => {
    if (state.tableData.filter(v => v.empNo === item.empNo).length === 0) {
      let time = data?.time;
      item.planStartTime = time[0];
      item.planEndTime = time[1];
      let startTime = time[0].split(" ")[0] ?? "";
      let endTime = time[1].split(" ")[0] ?? "";
      item.planTime = startTime + "至" + endTime;
      state.tableData.push(item);
    }
  });
  state.addStudentVisible = false;
};

const step2TableSelect = val => {
  state.tableSelectedData = val;
};

const handleEditPlan = val => {
  const row = val?.row;
  let planStartTime = row?.planStartTime ?? "";
  let planEndTime = row?.planEndTime ?? "";
  state.editPlanForm.time = [planStartTime, planEndTime];
  state.editPlanForm.index = val?.$index;
  state.editPlanVisible = true;
};

// 修改考试计划时间保存
const saveBtn = () => {
  let { index, time } = state.editPlanForm;
  let startTime = time[0].split(" ")[0] ?? "";
  let endTime = time[1].split(" ")[0] ?? "";
  state.tableData[index].planStartTime = time[0];
  state.tableData[index].planEndTime = time[1].split(" ")[0] + " 23:59:59";
  state.tableData[index].planTime = startTime + "至" + endTime;
  state.editPlanVisible = false;
};

const handleDeleteStudent = index => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      state.tableData.splice(index, 1);
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const handleResetStudent = item => {
  let data = item;
  let rowData = props?.rowData || {};
  PxMessageBox.confirm("是否重置该考生的考试次数、清空考试记录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params = {
        examId: rowData?.examId || "",
        examineeId: data?.row?.userId || ""
      };
      await resetExamTimesAPI(params);
      PxMessage.success("重置成功");
    })
    .catch(() => {});
};

// step3 查询
const handleSubjectQuery = () => {
  const { subjectType, subjectName } = state.queryParams;
  if (subjectType === "" && subjectName === "") {
    state.subjectTableData = state.data_back;
  } else {
    let data = [];
    if (subjectType !== "" && subjectName === "") {
      data = state.data_back.filter(item => item.type === subjectType);
    } else if (subjectType === "" && subjectName !== "") {
      data = state.data_back.filter(item => item.questionName.includes(subjectName));
    } else {
      data = state.data_back.filter(item => item.type === subjectType && item.questionName.includes(subjectName));
    }
    state.subjectTableData = data;
  }
};

// step3 重置
const resetSubjectQuery = () => {
  state.queryParams.subjectType = "";
  state.queryParams.subjectName = "";
  state.subjectTableData = state.data_back;
};

// step3 新增
const addQuestion = () => {
  state.addQuestionVisible = true;
};

// step3 从题库添加
const addQuestionFromBank = () => {
  state.addQuestionFromBankVisible = true;
};

// step3 自动组卷
const autoGroupQuestion = () => {
  state.addAutoGroupExamVisible = true;
};

const step3TableSelect = val => {
  state.subjectTableSelectedData = val;
};

// step3 删除
const handleDeleteSubject = index => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      state.subjectTableData.splice(index, 1);
      state.data_back = state.subjectTableData;
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

// step3 批量删除
const batchDeleteSubject = () => {
  if (state.subjectTableSelectedData.length === 0) {
    PxMessage.error("请选择要删除的数据");
    return;
  }
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const a1 = state.subjectTableData;
      const a2 = state.subjectTableSelectedData;
      state.subjectTableData = a1.filter(row => !a2.includes(row));
      state.data_back = state.subjectTableData;
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const saveQuestion = async data => {
  data.map(item => {
    if (state.subjectTableData.filter(v => v.questionId === item.questionId).length === 0) {
      state.subjectTableData.push(item);
    }
  });
  state.data_back = state.subjectTableData;
};

const editSearch = async () => {
  try {
    state.loading = true;
    const params = {
      examId: props.rowData.examId
    };
    const res = await getExamConfigAPI(params);
    state.editData = res;
    const base = res?.examineBase;
    state.baseForm = {
      name: base?.examName ?? "",
      type: base?.examCategoryId ?? "",
      className: base?.department ?? "",
      count: base?.examTimes,
      totalScore: base?.totalScore ?? "",
      passScore: base?.passScore ?? "",
      period: base?.duration ?? "",
      intruction: base?.intro ?? "",
      attention: base?.notice ?? ""
    };
    state.tableData = res.examinees.map(v => {
      return {
        realName: v?.examineeName ?? "",
        empNo: v?.workNo ?? "",
        deptName: v?.org ?? "",
        phone: v?.mobile ?? "",
        userId: v?.examineeId ?? "",
        createTime: v?.createTime ?? "",
        planStartTime: v?.planStartTime ?? "",
        planEndTime: v?.planEndTime ?? "",
        planTime: v?.planStartTime?.split(" ")[0] + "至" + v?.planEndTime?.split(" ")[0]
      };
    });
    state.subjectTableData = res.questions.map(v => {
      return {
        questionName: v?.questionName ?? "",
        typeName: v?.questionTypeName ?? "",
        score: v?.score ?? "",
        updateTime: v?.updateTime ?? "",
        updateByName: v?.updateByName ?? "",
        categoryId: v?.categoryId ?? "",
        questionId: v?.questionId ?? "",
        type: v?.questionType ?? "",
        answer: v?.answer ?? ""
      };
    });
    state.data_back = state.subjectTableData;
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const save = async () => {
  const params = {
    examId: props.handleType === "Add" ? null : props.rowData.examId,
    examineBase: {
      examId: props.handleType === "Add" ? null : props.rowData.examId,
      examName: state.baseForm.name,
      // categoryId: state.baseForm.type,
      examCategoryId: state.baseForm.type,
      department: state.baseForm.className,
      examTimes: state.baseForm.count,
      totalScore: state.baseForm.totalScore,
      passScore: state.baseForm.passScore,
      duration: state.baseForm.period,
      intro: state.baseForm.intruction,
      notice: state.baseForm.attention
    },
    examinees: state.tableData.map(item => {
      return {
        examId: props.handleType === "Add" ? null : props.rowData.examId,
        examineeName: item.realName,
        workNo: item.empNo,
        org: item.deptName,
        mobile: item.phone,
        examineeId: item.userId,
        planStartTime: item?.planStartTime ?? "",
        planEndTime: item?.planEndTime ?? ""
      };
    }),
    questions: state.subjectTableData.map((item, index) => {
      return {
        categoryId: item.categoryId,
        questionId: item.questionId,
        questionName: item.questionName,
        questionType: item.type,
        sort: index,
        score: item.score,
        answer: item.answer,
        assembleWay: "",
        updateByName: item.updateByName,
        updateTime: item.updateTime,
        // categoryName: "",
        questionTypeName: item.typeName,
        examid: props.handleType === "Add" ? null : props.rowData.examId
      };
    })
  };
  try {
    state.loading = true;
    await saveExamAPI(params);
    goBack();
    PxMessage.success(`${props.handleType === "Add" ? "新增" : "编辑"}成功`);
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const handleSubmit = async () => {
  const formValidate1 = await baseFormRef.value.validateField();
  const tableValidate = state.tableData.length > 0;
  const subjectTableValidate = state.subjectTableData.length > 0;
  let total = 0;
  state.subjectTableData.forEach(item => {
    total += item.score;
  });
  if (Number(total) !== Number(state.baseForm.totalScore)) {
    PxMessage.error("题目总分与试卷总分不一致，请调整");
    return;
  }
  if (Number(total) > Number(state.baseForm.totalScore)) {
    PxMessage.error("题目总分不能超过试卷总分");
    return;
  }
  if (formValidate1 && tableValidate && subjectTableValidate) {
    save();
  } else {
    PxMessage.error("所需数据不完整，请检查");
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");

.config-step {
  position: relative;
  width: 100%;

  .back-btn {
    position: absolute;
    left: 0;
  }

  .step-container {
    width: 400px;
    margin: 0 auto;
  }

  .step-form {
    position: relative;
    width: 80%;
    height: calc(100vh - 240px);
    padding: 40px 0 20px;
    margin: 0 auto;
  }

  .step-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}

.table-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.preview-content {
  width: 100%;
  height: calc(100vh - 450px);
}

.topic-info-title {
  font-size: 16px;
  font-weight: bold;

  .topic-info {
    margin-right: 32px;
  }
}

.over-score {
  color: #ef4444;
}

.cell-title {
  display: flex;
  align-items: center;
  justify-content: center;

  .px-icon {
    color: rgb(59 130 246);
  }
}
</style>
